from sqlalchemy import Column, String, Text, BigInteger, DateTime, Integer
from sqlalchemy.sql import func
from src.models.base import BaseModel
from datetime import datetime
from typing import Optional

class Works(BaseModel):
    """媒体作品数据模型"""
    __tablename__ = 'works'
    
    # 平台信息
    platform_type = Column(String(10), nullable=False, default='douyin', comment='平台类型')
    platform_name = Column(String(50), nullable=False, default='抖音', comment='平台名称')
    
    # 达人信息
    kol_name = Column(String(200), comment='达人名称')
    kol_avatar = Column(String(500), comment='达人头像')
    kol_platform_id = Column(String(50), comment='达人的平台ID')
    
    # 作品信息
    title = Column(String(500), comment='笔记/视频标题')
    type = Column(String(255), default='image', comment='作品类型：image-图文，video-视频')
    images = Column(Text, comment='图片链接，多个图片用逗号隔开')
    video = Column(Text, comment='视频链接')
    cover = Column(String(500), comment='视频封面')
    tags = Column(String(1000), comment='笔记/视频附带的标签')
    content = Column(Text, comment='作品内容描述')
    
    # 时间信息
    release_time = Column(DateTime, comment='笔记/视频的发布时间')
    
    # 链接信息
    source_link = Column(Text, nullable=False, comment='笔记/视频的源链接')
    
    # 统计信息
    comment_count = Column(BigInteger, default=0, comment='评论数')
    collect_count = Column(BigInteger, default=0, comment='收藏数')
    like_count = Column(BigInteger, default=0, comment='点赞数')
    share_count = Column(BigInteger, default=0, comment='分享数')
    
    def __repr__(self):
        return f"<Works(id={self.id}, title='{self.title}', platform='{self.platform_type}')>"
    
    def to_dict(self, exclude_fields: list = None) -> dict:
        """转换为字典格式"""
        result = super().to_dict(exclude_fields)
        
        # 处理特殊字段
        if self.release_time:
            result['release_time'] = self.release_time.isoformat()
            
        return result
    
    @classmethod
    def from_douyin_data(cls, dy_data: dict, source_url: str) -> 'Works':
        """从抖音数据创建Works实例
        
        Args:
            dy_data: 抖音数据字典
            source_url: 原始请求URL
            
        Returns:
            Works实例
        """
        # 时间戳转换为datetime
        release_time = None
        if dy_data.get('create_time'):
            try:
                release_time = datetime.fromtimestamp(int(dy_data['create_time']))
            except (ValueError, TypeError):
                pass
        
        # 判断作品类型
        work_type = 'video' if dy_data.get('format') == 'mp4' else 'image'
        
        # 处理图片数据
        images = None
        if dy_data.get('images') and isinstance(dy_data['images'], list):
            images = ','.join(dy_data['images'])
        
        return cls(
            platform_type='douyin',
            platform_name='抖音',
            kol_name=dy_data.get('author', ''),
            kol_platform_id=dy_data.get('sec_uid', ''),
            title=dy_data.get('title', ''),
            type=work_type,
            images=images,
            video=dy_data.get('videoUrl'),
            cover=dy_data.get('cover'),
            tags=dy_data.get('hashtagNames', ''),
            release_time=release_time,
            source_link=source_url,
            comment_count=dy_data.get('comment_count', 0),
            collect_count=dy_data.get('collect_count', 0),
            like_count=dy_data.get('like_count', 0),
            share_count=dy_data.get('share_count', 0)
        )